$(function() {
	var catsNumber = 5;
	var parallax = 109;
	
	var catBlocks = new Object();
	catBlocks.catNum = 0;
	catBlocks.getCategoryName = function(index) {
		for(var cat in this)
		{
			if(this[cat].index == index)
				return cat;
		}
	};
	createCatsObject(catBlocks);
	
	var car_params = {
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					scroll: {
						duration: 150,
					},
					items: {
						width: 160,
						height: 80,
						visible: {
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						items: 1
					}
	};
	
	$('.b-elements').carouFredSel(car_params);
	
	$('.mini-prew').carouFredSel({
					responsive: true,
					width: '40%',
					height: 36,
					auto: false,
					scroll: {
						duration: 150,
					},
					items: {
						width: 77,
						height: 36,
						visible: {
							min: 1,
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						items: 1
					}
	});

	
	$(window).resize(resizeActivePage);
	
	//Backbone--------------------------------------------------------------------------
	
	var Controller = Backbone.Router.extend({
		routes: {
			"": "main",
			"!/": "main",
			//"!/:page": "page",
			"!/first": "first",
			"!/second": "second",
			"!/category/:cat": "category",
			"!/category/up/:cat/:num": "categoryUp"
        },
		
		categoryUp: function(cat, num) {
			//allBlocksDown(parallax, true);
			moveBlockUp(catBlocks, cat, num, parallax, true);
		},
		
		main: function() {
			allBlocksDown(parallax, false);
			//moveBlockUp(catBlocks, 'titles', 3, parallax, true);
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#main').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#main').slideDown(1500);*/
			
			//$('#main').css({display:'block'});
			//$('#all_blocks').animate({left:'+' + $('#all_blocks').css('width')});
			/*$('.activePage').css({display:"none"});
			$('.activePage').removeClass('activePage');
			$('#main').addClass('activePage');*/
			
			if (!$('#main').hasClass('activePage'))
			{
				$('.activePage').css({zIndex:"100"});
				$('.activePage').removeClass('activePage');
				$('#main').addClass('activePage');
				$('.activePage').css({zIndex:"101"});
				$('#all_pages').animate({left: 0}, 1500);
			}
		},
		
		/*page: function(page) {
			//alert(page);
			var page_id = '#' + page;
			var prevActivePage_id = '#' + $('.activePage').attr('id');
			$(prevActivePage_id).removeClass('activePage');
			$(page_id).addClass('activePage');
			//$(page_id).animate({left:'-' + $('#all_pages').css('width')}, 1500);
			$(page_id).animate({left:'0'}, 1500);
			$(page_id).css('width', '100%');
			$(prevActivePage_id).css('left', '100%');
		},*/
		
		first: function() {
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#first').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#first').slideDown(1500);*/
			
			$('.activePage').css({zIndex:"100"});
			$('.activePage').removeClass('activePage');
			$('#first').addClass('activePage');
			$('.activePage').css({zIndex:"101"});
			$('#all_pages').animate({left:'-' + $('#all_pages').css('width')}, 1500);
			$('#first').css('width', '100%');
		},
		
		second: function() {
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#second').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#second').slideDown(1500);*/
			
			//$('#second').css({display:'block'});
			//$('#all_blocks').animate({left:'+' + $('#all_blocks').css('width')});
			/*$('.activePage').css({display:"none"});
			$('.activePage').removeClass('activePage');
			$('#second').addClass('activePage');*/
			
			$('.activePage').css({zIndex:"100"});
			$('.activePage').removeClass('activePage');
			$('#second').addClass('activePage');
			$('.activePage').css({zIndex:"101"});
			$('#all_pages').animate({left:'-' + $('#all_pages').css('width')}, 1500);
			$('#second').css('width', '100%');
		},
		
		category: function (cat) {
			var cat_class = '.' + cat;
			var classes = $(cat_class).attr('class');

			$('.loaded-uls').slideUp(1000);
			
			$(cat_class + ':first').after($('.loaded-uls'));
			
			$('.loaded-uls .row-category').each(function() {
				$(this).html($(cat_class + ':first .caroufredsel_wrapper').html());
				$(this).attr('class', classes);
				$(this).children('ul').removeAttr('style');
				//$(this).carouFredSel(car_params);
			});			
			
			$('.loaded-uls .row-title').remove();
			
			$(cat_class + ':first').slideDown(1000);
			$('.loaded-uls').slideDown(1000);
			
			$('.loaded-uls').prev('.row-category').prevAll('.row-category').slideUp(1000);
			//console.log($('.loaded-uls').prev('.row-category').prevAll('.row-category').get().reverse());
			$($('.loaded-uls').prev('.row-category').prevAll('.row-category').get().reverse()).each(function() {
				if ($('.loaded-uls').nextAll('.row-category').size() > 0)
				{
					$('.loaded-uls').nextAll('.row-category:last').after($(this));
				}
				else
				{
					$('.loaded-uls').after($(this));
				}
			});
			$('.loaded-uls').next('.row-category').nextAll('.row-category').slideUp(1000);
			$('.loaded-uls').next('.row-category').slideDown(1000);

			$('.loaded-uls .b-elements').carouFredSel(car_params);
			$(cat_class + ' .b-elements:first').trigger("synchronise", ".loaded-uls .b-elements");
		}
	});
	
	var controller = new Controller();

	Backbone.history.start();
});

function resizeActivePage()
{
	/*if (!$('#main').hasClass('activePage'))
		$('#all_pages').css('left', '-' + $('#all_pages').css('width'));*/
}

function isActivePage(page_id)
{
	if ($('#' + page_id).hasClass('activePage'))
		return true;
	return false;
}

//console.log($('.category').eq(3).attr('class'));

function allBlocksDown(parallaxVal, animate)
{
	var one_parallax = 0;
	var animateTime = 2000;
	
	if (!animate)
		animateTime = 0;
		
	$('.category').each(function() {
		$(this).animate({top: one_parallax}, animateTime);
		one_parallax += parallaxVal;
	});
}

/*
	(Array(object)) catObjects - ассоциативный массив объектов с описанием категорий
	(string) block - id сдвигаемого блока
	(int) upNum - количество позиций для сдвига
	(int) parallaxVal - высота одного слайдера
	(bool) animate - анимированный сдвиг (true) или нет (false)
*/

function moveBlockUp(catObjects, block, upNum, parallaxVal, animate)
{
	var firstCatID = '#' + $('.category').eq(0).attr('id');
	console.log(firstCatID);
	var blockID = '#' + block;
	var currentCatZindex = $(blockID).css('z-index');
	
	$(blockID).stop(false, false);
	//var upPixels = $(blockID).css('top') - upNum * parallaxVal;
	var futureIndex = 0;
	//var shift = upNum;
	if (catObjects[block].index > upNum)
	{
		futureIndex = catObjects[block].index - upNum;
	}
	/*else if (catObjects[block].index - upNum < 0)
	{
		shift = catObjects[block].index;
	}*/
			
	console.log(futureIndex);
		
	var upPixels = catObjects[block].index*parallaxVal - upNum * parallaxVal;
	
	if (upPixels < 0)
	{
		upPixels = 0;
	}
	
	var animateTime = 2000;
	
	if (!animate)
		animateTime = 0;
	
	$(blockID).animate({top: upPixels}, animateTime, function() {
		/*console.log(shift);
        for (var i=0; i!=shift; ++i) {
            var temp = catObjects[catObjects.getCategoryName(i)];
            for (var j=i; j!=catObjects.catNum-1; ++j) {
				console.log(j);
				catObjects[catObjects.getCategoryName(j)].zIndex = catObjects[catObjects.getCategoryName(j+1)].zIndex;
				catObjects[catObjects.getCategoryName(j)].index = catObjects[catObjects.getCategoryName(j+1)].index;
            }
           catObjects[catObjects.getCategoryName(catObjects.catNum-1)].index =  temp.index;
		   catObjects[catObjects.getCategoryName(catObjects.catNum-1)].zIndex = temp.zIndex;
        }
       
	   console.log(catObjects);
	   
	   var one_parallax = parallaxVal * shift + parseInt($(blockID).css('top'));
	   console.log(one_parallax);
	   $($(blockID).prevAll('.category').get().reverse()).each(function() {
			if ($(blockID).nextAll('.category').size() > 0)
			{
				$(blockID).nextAll('.category:last').after($(this));
			}
			else
			{
				$(blockID).after($(this));
			}
			
			$(this).animate({top: one_parallax}, animateTime);
			one_parallax += parallaxVal;
		});*/
	});
	//$(blockID).stop();
	//дальше смена свойств сдвигаемого объекта и тех, которые он перекрыл + их перемещение
}

function createCatsObject(object)
{
	$('.category').each(function() {
		var catID = $(this).attr('id');
		object[catID] = new Object();
		object[catID].zIndex = $(this).css('z-index');
		//object[catID].visibleRows = 1;
		object[catID].index = $(this).index();
		object.catNum++;
	});
}